package logview;

import java.io.File;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ConfigFilter implements Filter {
	private static transient final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(ConfigFilter.class);
	private String filename;
	
	public void destroy() {
		log.debug(ConfigFilter.class.getName()+" destroyed");	
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
		if (isConfigured()) {
			log.debug("isConfigured: continue");
			arg2.doFilter(arg0, arg1);
		} else {
			log.debug("isConfigured: redirecting to config url");
			arg0.setAttribute("message", "Application must be initialized by writing logfiles.properties content");
			arg0.getRequestDispatcher("/edit").forward(arg0, arg1);
		}
	}

	private boolean isConfigured() {
		final File f = new File(filename);
		return f.exists() && f.canRead() && f.canWrite();
	}

	public void init(FilterConfig config) throws ServletException {
		filename = config.getServletContext().getRealPath("WEB-INF/logfiles.properties");
		log.debug(ConfigFilter.class.getName()+" initialized");
	}

}
